package com.nenglai.admin.modular.report.util;

import com.nenglai.admin.modular.report.enums.UploadServiceEnum;
import com.nenglai.admin.modular.report.service.upload.Upload;
import com.nenglai.admin.util.COSClientUtil;
import com.nenglai.common.response.ErrorCode;
import com.nenglai.common.response.ResponseException;
import com.nenglai.common.util.FileUtil;
import com.nenglai.common.util.SpringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @author kongdehui
 * @date 2021/06/18 16:12
 **/
@Component
public class ReportUtil {

    @Resource
    COSClientUtil cosClientUtil;

    /**
     * @param file 上传文件
     * @return 上传文件名称
     * @throws IOException
     */
    public String uploadTemplate(MultipartFile file, String service, String path, String name) throws Exception {
        String suffix = FileUtil.suffix(Objects.requireNonNull(file.getOriginalFilename()));
        if (!"docx".equals(suffix) && !"doc".equals(suffix)) {
            throw new ResponseException(ErrorCode.JUST_SUPPORT_DOCX);
        }
        String filename = name + "." + suffix;
        Upload upload = SpringUtil.getBean(service, Upload.class);
        upload.upload(file, path, filename);
        return path + "/" + filename;
    }

    /**
     * 删除上传图片
     *
     * @param service
     * @param filepath
     */
    public void clearFile(String service, String filepath) {
        if (UploadServiceEnum.UPLOAD_LOCAL.getCode().equals(service)) {
            File file = new File(filepath);
            file.delete();
        }
        if (UploadServiceEnum.UPLOAD_COS.getCode().equals(service)) {
            cosClientUtil.deleteObject(filepath);
        }
    }
}
